/*
 * @Author       : NaN 353362604@qq.com
 * @Date         : 2023-05-08 17:00:33
 * @LastEditTime : 2023-08-03 10:21:36
 * @LastEditors  : NaN 353362604@qq.com
 * @FilePath     : \AdminStration\src\Pages\Front\Assets\Template\ProjectMap.jsx
 * @Description  :
 */
import './Scss/ProjectMap.scss'
import { useRef, useEffect, useState } from 'react'
import { useEventEmitter, useRequest } from 'ahooks'
import { Initialization, InitializationData } from '../../../../Common/Mars3d/Initialization'
import { Http } from '../../../../Common/Api'
import { WebTemplateUrl } from './configuration'
import { TemplateMapDivList } from './TemplateMap/TemplateMapDivList'
import { useLatest } from '@ant-design/pro-components'

const { mars3d, location } = window
const { hostname } = location

// 默认处理
export const ProjectMap001 = ({ sceneId, MapClickEvent, style, ElementKML, DataEvent, MapData, defaultValue }) => {
    const [Map, setMap] = useState()
    const [Gra, setGra] = useState()
    const Mars3dBox = useRef()
    const InitializationEvent = useEventEmitter()
    InitializationEvent.useSubscription(({ map, gra, uuid }) => {
        setMap(map)
        setGra(gra)
        map.on('click', e => MapClickEvent.emit({ type: 'map', data: e }))
        getScenesDetails({ url: `getScenesDetailsUuid`, path: [uuid] }).then(res => {
            // 各项目的额外数据处理
            InitializationData(map, gra, res, true)
            if (defaultValue)
                MapClickEvent.emit({
                    type: Object.keys(defaultValue)[0],
                    data: defaultValue[Object.keys(defaultValue)],
                })
            switch (hostname) {
                case 'jjt.ljkjkf.com':
                    const { elements } = res
                    const KMLList = elements.filter(v => v.elementType === 'kmlList')
                    DataEvent.emit(KMLList.flatMap(({ elementDetails }) => elementDetails))
                    const typeList = ['point', 'div']
                    const { StyleOne, StyleTwo } = style
                    const ELEMENT_DATA = elements.filter(
                        v =>
                            typeList.includes(v.elementType) &&
                            v.elementUuid !== '66197e4d-d7f5-40aa-b42b-802a7d0db943',
                    )
                    ELEMENT_DATA.forEach(({ elementType, elementDetails }) => {
                        elementDetails.forEach(({ elementDetailUuid }) => {
                            console.log(elementDetailUuid)
                            if (elementType === 'point') gra.getGraphicById(elementDetailUuid).setStyle(StyleOne)
                            if (elementType === 'div') gra.getGraphicById(elementDetailUuid).setStyle(StyleTwo)
                        })
                    })
                    break
                default:
                    break
            }
        })
    })
    const { runAsync: getScenesDetails } = useRequest(Http, { manual: true })
    const { runAsync: getSupervise } = useRequest(Http, { manual: true })
    const { run: getScenes } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            Initialization(res, Mars3dBox, InitializationEvent)
        },
    })

    MapClickEvent?.useSubscription(val => {
        const { type, data } = val
        const { center, uuid, url, classDiv } = data
        if (!Map || !Gra) return
        switch (type) {
            case 'jjtCenter':
                const mapList = Map.getLayersByAttr('kml', 'type')
                mapList.forEach(item => {
                    if (ElementKML[uuid].includes(item.uuid)) item.setOptions({ show: true })
                    else item.setOptions({ show: false })
                })
                Map.centerAt(JSON.parse(center))
                break
            case 'jjtKml':
                Map.flyTo(Map.getLayerById(uuid))
                break
            case 'IsShow':
                const hide = Object.keys(MapData)
                    .filter(e => !data.includes(e))
                    .concat(data.filter(e => !Object.keys(MapData).includes(e)))
                data.forEach(item =>
                    MapData[item].elem.forEach(uuid => Gra.getGraphicById(uuid).setOptions({ show: true })),
                )
                hide.forEach(item =>
                    MapData[item].elem.forEach(uuid => Gra.getGraphicById(uuid).setOptions({ show: false })),
                )
                break
            case 'Supervise':
                const Supervise = new mars3d.layer.GraphicLayer({ id: 'Supervise' })
                if (Map.getLayerById('Supervise')) Map.removeLayer(Map.getLayerById('Supervise'))
                Map.addLayer(Supervise)
                getSupervise({ url, data: { OrganizationUuid: uuid, pageIndex: 1, pageSize: 100000 } }).then(res => {
                    res.list.forEach(item =>
                        Supervise.addGraphic(
                            new mars3d.graphic.DivGraphic(TemplateMapDivList[classDiv]({ data: item })),
                        ),
                    )
                    if (Supervise.graphics.length !== 0) Map.flyToGraphic(Supervise.graphics, { radius: 2000 })
                    else Map.centerAt({ lat: 25.282174, lng: 110.443587, alt: 6056169.5, heading: 348.9, pitch: -78.9 })
                })
                break
            default:
                break
        }
    })

    useEffect(() => {
        getScenes({ url: `getScenesID`, path: [sceneId] })
    }, [getScenes, sceneId])
    return (
        <div className="ProjectMap001">
            <div ref={Mars3dBox} />
            <img src={WebTemplateUrl + 'Mask.png'} alt="" />
        </div>
    )
}

// 判断系那是
export const ProjectMap002 = ({ sceneId, MapDataEvent }) => {
    const [Map, setMap] = useState()
    const [Gra, setGra] = useState()

    const Mars3dBox = useRef()
    const InitializationEvent = useEventEmitter()
    InitializationEvent.useSubscription(({ map, gra, uuid }) => {
        setMap(map)
        setGra(gra)
    })
    const { runAsync: getScenesDetails } = useRequest(Http, { manual: true })
    const { run: getScenes } = useRequest(Http, {
        manual: true,
        onSuccess: res => Initialization(res, Mars3dBox, InitializationEvent),
    })

    const drawMap = async val => {
        if (Gra && Map) {
            const { Active, customData } = val
            Gra.clear()
            if (customData) {
                getScenesDetails({
                    url: `getDetailsByOrganizationUuid`,
                    data: { uuid: sceneId, OrganizationUuid: Active },
                }).then(res => {
                    InitializationData(Map, Gra, res, true)
                    const [{ one }] = JSON.parse(customData)
                    Map.centerAt(JSON.parse(one))
                })
            } else Map.centerAt({ lat: 44.780855, lng: 127.740888, alt: 1870845.7, heading: 356.4, pitch: -77.9 })
        } else setTimeout(() => drawMap(val), 500)
    }

    MapDataEvent.useSubscription(val => {
        drawMap(val)
    })

    useEffect(() => {
        getScenes({ url: `getScenesID`, path: [sceneId] })
    }, [getScenes, sceneId])
    return (
        <div className="ProjectMap001">
            <div ref={Mars3dBox} />
            <img src={WebTemplateUrl + 'Mask.png'} alt="" />
        </div>
    )
}
